layui.use(['element','table','form','layer','util','laydate'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer;

    function loadOptions(url, projectId,eleId) {
        $.get(url, {projectId:projectId}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>全部</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item + "'>" + item + "</option>";
                    });
                    $("#"+eleId).empty().append($opt_html);
                    form.render('select');
                }
            }
        });
    }

    function loadCategoryList(projectId) {
        $.get('/cdacscontrolmgr/cdacscontrolmgrCarRecord/listCategory', {projectId:projectId}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>全部</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item + "'>" + item + "</option>";
                    });
                    $("#categoryId").empty().append($opt_html);
                    form.render('select');
                }
            }
        });
    }

    //执行一个laydate实例
    var beginDateInit = function(startId,endId ){
        laydate.render({
            elem: startId,
            type: 'datetime',
            done: function (value ) {
                var startDate = new Date(value).getTime();
                var endTime = new Date($(endId).val()).getTime();
                if (endTime < startDate) {
                    layer.msg('结束时间不能小于开始时间');
                    $(startId).val('');
                }
            }
        })
    }
    var endDateInit = function(startId,endId ){
        laydate.render({
            elem: endId,
            type: 'datetime',
            done: function (value ) {
                var startDate = new Date($(startId).val()).getTime();
                var endTime = new Date(value).getTime();
                if (endTime < startDate) {
                    layer.msg('结束时间不能小于开始时间');
                    $(endId).val('');
                }
            }
        })
    }

    // 行人记录开门时间
    beginDateInit('#openBeginDate','#openEndDate');
    endDateInit('#openBeginDate','#openEndDate');

    // 进出时间
    beginDateInit('#openBeginDate2','#openEndDate2');
    endDateInit('#openBeginDate2','#openEndDate2');
    // 行人来访记录开门时间
    beginDateInit('#openBeginDate3','#openEndDate3');
    endDateInit('#openBeginDate3','#openEndDate3');
    // 车行来访记录通行时间
    beginDateInit('#openBeginDate4','#openEndDate4');
    endDateInit('#openBeginDate4','#openEndDate4');

    laydate.render({
        elem: '#capDate',
        type: 'date',
        trigger: 'click' //采用click弹出
    });

    table.render({
        elem: '#myYardTable'
        ,url:'/cdacscontrolmgr/cdacscontrolmgrMyProject/list'
        ,title: '项目管理'
        ,where: {}
        ,cols: [[
            {field: 'xh',type:'numbers', title: '序号',}
            ,{field:'projectNo', title:'项目编号',align:'center'}
            ,{field:'projectName', title:'项目名称',align:'center'}
            ,{field:'managerName', title:'负责人',align:'center'}
            ,{field:'managerPhone', title:'联系电话',align:'center'}
            ,{field:'addressDetail', title:'项目位置',align:'center'}
            ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',fixed: 'right',width:500}
        ]]
        ,page: true
        ,toolbar: '#toolbarDemo'
    });

    table.on('tool(myYardTable)',function (obj) {
        var data = obj.data;
        let projectId = data.id;
        switch (obj.event) {
            case 'xrjl':
                renderXrRecord(projectId);
                break;
            case 'cxjl':
                renderCxRecord(projectId);
                break;
            case 'xrlfjl':
                renderXrlfRecord(projectId);
                break
            case 'cxlfjl':
                renderCxlfRecord(projectId);
                break
            case 'snapRecord':
                renderSnapRecord(projectId);
                break
            case 'carInside':
                renderCarInsideRecord(projectId);
                break

        }
    });

    function renderCarInsideRecord(projectId) {
        $("#projectId").val(projectId);
        table.render({
            elem: '#carInsideTable'
            ,url:'/cdyardmgr/cdyardmgrPassRecord/pageCarInside'
            ,title: '场内车辆记录'
            ,where: {"projectId":projectId}
            ,cols: [[
                {type:'checkbox'},
                {type:'numbers',title:'序号'}
                ,{field:'carNo', title:'车牌号',align:'center'}
                ,{field:'category', title:'车辆类别',align:'center'}
                ,{field:'enterTime', title:'入场时间',  sort: true,templet:
                        function(data){
                            return formatTime(data.enterTime);
                        }}
                ,{field:'stayTimeStr', title:'已停留时间',align:'center'}
                ,{field:'phone', title:'车主手机号码',align:'center'}
            ]]
            ,page:true
            ,toolbar: '#toolbarDemo'
            ,parseData: function(res){ //res 即为原始返回的数据
                $("#carInsideTotal").html(res.carNum);
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }
        });
        layer.open({
            type: 1
            , title: '场内车辆'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#carInsideDiv')
            ,btn: ['确定', '取消']
        });
    }
    $("#artificialCorrect").on('click',function () {
        let checkStatus = table.checkStatus('carInsideTable');
        let data= checkStatus.data
        if(data.length == 0){
            layer.msg("请选择需要纠正的车辆");
            return false;
        }
        $("#carInsideId").val(data[0].id);
        $("#remark").val("");
        layer.open({
            type: 1
            , title: '人工纠正'
            , shadeClose: true
            , area: ['60%', '80%']
            , content: $('#artificialCorrectDiv')
            ,btn: ['确定', '取消']
            ,yes: function(index, layero){
                let load = layer.load();
                let arr = [];
                for (let i = 0; i < data.length; i++) {
                    arr.push({"id":data[i].id,"remark":$("#remark").val(),"carNo":data[i].carNo,"projectId":data[i].projectId});
                }
                //let param = {"id":$("#carInsideId").val(),"remark":$("#remark").val(),"isDel":1};
                $.ajax({
                    type: 'post',
                    url: '/cdyardmgr/cdyardmgrPassRecord/correctCar',
                    contentType: "application/json;charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(arr),
                    success: function (res) {
                        layer.close(load);
                        layer.msg(res.msg);
                        if(res.status == 200){
                            layer.close(index);
                            table.reload('carInsideTable');
                        }
                    },
                });
            }
        });
    });

    form.on('submit(queryCarInside)',function () {
        queryCarInside();
        return false;
    });

    function queryCarInside(){
        var projectId = $("#projectId").val();
        var carNo = $("#searchCarNo3").val();
        var sjfw = $("#stayTime").val();
        table.reload('carInsideTable',{
            where: {projectId:projectId,carNo:carNo,sjfw:sjfw}
            ,page:  {
                curr:1
            }
        });
    }


    function renderSnapRecord(yardId) {
        $("#yardId2").val(yardId);
        table.render({
            elem: '#snapRecordTable'
            ,url:'/cdyardmgr/cdyardmgrPassRecord/listSnapRecord'
            ,title: '抓拍记录'
            ,where: {"yardId":yardId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'createTime', title:'时间',  sort: true,templet:
                        function(data){
                            return formatTime(data.createTime);
                        }}
                ,{field:'signoName', title:'抓拍门禁',align:'center'}
                ,{field: 'capPic', title: '抓拍图片', align:'center',templet:function (d) {
                        if(d.capPic){
                            return '<img onclick="previewImg(this)" style="cursor: pointer" width="30" height="25" src="'+d.capPic+'"/>';
                        }
                        return "";
                    }}
            ]]
            ,page:true
        });
        layer.open({
            type: 1
            , title: '抓拍记录'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#snapRecordDiv')
            ,btn: ['确定', '取消']
        });
    }

    form.on('submit(querySnapRecord)',function () {
        querySnapRecord();
        return false;
    });

    function querySnapRecord(){
        var capDate = $("#capDate").val();
        var yardId = $("#yardId2").val();
        table.reload('snapRecordTable',{
            where: {capDate:capDate,yardId:yardId}
            ,page:  {
                curr:1
            }
        });
    }

    function renderXrRecord(projectId) {
        $("#xrProjectId").val(projectId);
        loadOptions('/cdacscontrolmgr/cdacscontrolmgrXrRecord/listAcsOptions',projectId,'acsName');
        table.render({
            elem: '#xrRecordTable'
            ,url:'/cdacscontrolmgr/cdacscontrolmgrXrRecord/list'
            ,title: '行人记录'
            ,where: {"projectId":projectId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'openUser', title:'开门人',align:'center'}
                ,{field:'openUserSf', title:'开门人身份',align:'center'}
                ,{field:'phone', title:'联系电话',align:'center'}
                ,{field:'acsName', title:'开启门禁',align:'center'}
                ,{field:'openType', title:'开门方式',align:'center'}
                ,{field:'openTime', title:'开门时间', sort: true,templet:
                        function(data){
                            return formatTime(data.openTime);
                        }}
                ,{field:'right',title:'操作',toolbar:'#barOperate2',align:'center',fixed: 'right'}
            ]]
            ,page:true
            ,toolbar: '#toolbarDemo'
        });
        layer.open({
            type: 1
            , title: '行人记录'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#xrRecordDiv')
            ,btn: ['确定', '取消']
        });
    }

    function renderCxRecord(projectId) {
        $("#cxProjectId").val(projectId);
        loadOptions('/cdacscontrolmgr/cdacscontrolmgrCarRecord/listBarrierOptions',projectId,'signoName');
        loadCategoryList(projectId);
        table.render({
            elem: '#cxRecordTable'
            ,url:'/cdacscontrolmgr/cdacscontrolmgrCarRecord/list'
            ,title: '车行记录'
            ,where: {"projectId":projectId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'carNo', title:'车牌号',align:'center'}
                ,{field:'category', title:'车辆类别',align:'center'}
                ,{field:'jcfs', title:'进出方式',align:'center'}
                ,{field:'signoName', title:'经过道闸',align:'center'}
                ,{field:'direction', title:'进出方向',align:'center'}
                ,{field:'passTime', title:'时间', sort: true,templet:
                        function(data){
                            return formatTime(data.passTime);
                        }}
                ,{field:'remark', title:'备注',align:'center'}
                ,{field:'right',title:'操作',toolbar:'#barOperate2',align:'center',fixed: 'right'}
            ]]
            ,page:true
            ,toolbar: '#toolbarDemo'
        });
        layer.open({
            type: 1
            , title: '车行记录'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#cxRecordDiv')
            ,btn: ['确定', '取消']
        });
    }

    function renderXrlfRecord(projectId) {
        $("#xrlfProjectId").val(projectId);
        table.render({
            elem: '#xrlfRecordTable'
            ,url:'/cdacscontrolmgr/cdacscontrolmgrXrlfRecord/list'
            ,title: '行人来访记录'
            ,where: {"projectId":projectId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'owner', title:'业主',align:'center'}
                ,{field:'phone', title:'手机号',align:'center'}
                ,{field:'visitor', title:'来访人',align:'center'}
                ,{field:'visitTime', title:'来访时间',align:'center'}
                ,{field:'acsName', title:'开启门禁',align:'center'}
                ,{field:'openTime', title:'开门时间', sort: true,templet:
                        function(data){
                            return formatTime(data.openTime);
                        }}
                //,{field:'temPassword', title:'临时密码',align:'center'}
                ,{field:'right',title:'操作',toolbar:'#barOperate2',align:'center',fixed: 'right'}
            ]]
            ,page:true
            ,toolbar: '#toolbarDemo'
        });
        layer.open({
            type: 1
            , title: '行人来访记录'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#xrlfRecordDiv')
            ,btn: ['确定', '取消']
        });
    }

    function renderCxlfRecord(projectId) {
        $("#cxlfProjectId").val(projectId);
        table.render({
            elem: '#cxlfRecordTable'
            ,url:'/cdacscontrolmgr/cdacscontrolmgrCxlfRecord/list'
            ,title: '车行来访记录'
            ,where: {"projectId":projectId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'owner', title:'业主',align:'center'}
                ,{field:'phone', title:'手机号',align:'center'}
                ,{field:'carNo', title:'车牌号',align:'center'}
                ,{field:'visitTime', title:'来访时间',align:'center'}
                ,{field:'signoName', title:'通行道闸',align:'center'}
                ,{field:'passTime', title:'通行时间', sort: true,templet:
                        function(data){
                            return formatTime(data.passTime);
                        }}
                ,{field:'right',title:'操作',toolbar:'#barOperate2',align:'center',fixed: 'right'}
            ]]
            ,page:true
            ,toolbar: '#toolbarDemo'
        });
        layer.open({
            type: 1
            , title: '车行来访记录'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#cxlfRecordDiv')
            ,btn: ['确定', '取消']
        });
    }

    table.on('tool(xrRecordTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'image':
                let base64Img = data.picture;
                if(!base64Img.startsWith("data:image/")){
                    base64Img = "data:image/jpeg;base64," + base64Img;
                }
                srcPicture(base64Img,'人脸照片');
                break;

        }
    });
    table.on('tool(cxRecordTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'image':
                srcPicture(data.picture,'图像记录');
                break;

        }
    });

    table.on('tool(xrlfRecordTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'image':
                let base64Img = data.facePicture;
                if(!base64Img.startsWith("data:image/")){
                    base64Img = "data:image/jpeg;base64," + base64Img;
                }
                srcPicture(base64Img,'人脸照片');
                break;

        }
    });

    table.on('tool(cxlfRecordTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'image':
                srcPicture(data.picture,'图像记录');
                break;

        }
    });

    function srcPicture(path,title) {
        $("#picture").attr("src",path);
        layer.open({
            type: 1
            , title: title
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#imageDiv')
            ,btn: ['确定', '取消']
        });
    }

    function formatTime(data){
        return data ? data.replace("T", " "):"";
    }

    form.on('submit(queryYard)',function () {
        queryYard();
        return false;
    });

    form.on('submit(queryXrRecord)',function () {
        queryXrRecord();
        return false;
    });

    form.on('submit(queryCxRecord)',function () {
        queryCxRecord();
        return false;
    });

    form.on('submit(queryXrlfRecord)',function () {
        queryXrlfRecord();
        return false;
    });

    form.on('submit(queryCxlfRecord)',function () {
        queryCxlfRecord();
        return false;
    });

    function queryYard(){
        var projectName = $("#searchName").val();
        var projectNo = $("#searchCode").val();
        table.reload('myYardTable',{
            where: {projectName:projectName,projectNo:projectNo}
            ,page:  {
                curr:1
            }
        });
    }

    function queryXrRecord(){
        var projectId = $("#xrProjectId").val();
        var openUser = $("#searchOpenUser").val();
        var phone = $("#searchPhone").val();
        var acsName = $("#acsName").val();
        var openUserSf = $("#openUserSf").val();
        var openType = $("#openType").val();
        var startDate= $("#openBeginDate").val();
        var endDate= $("#openEndDate").val();
        table.reload('xrRecordTable',{
            where: {projectId:projectId,openUser:openUser,phone:phone,acsName:acsName,openUserSf:openUserSf,
                openType:openType,startDate:startDate,endDate:endDate}
            ,page:  {
                curr:1
            }
        });
    }

    function queryCxRecord() {
        var projectId = $("#cxProjectId").val();
        var carNo = $("#searchCarNo").val();
        var signoName = $("#signoName").val();
        var category = $("#categoryId").val();
        var direction = $("#direction").val();
        var startDate= $("#openBeginDate2").val();
        var endDate= $("#openEndDate2").val();
        table.reload('cxRecordTable',{
            where: {projectId:projectId,carNo:carNo,signoName:signoName,category:category,direction:direction,
                startDate:startDate,endDate:endDate}
            ,page:  {
                curr:1
            }
        });
    }

    function queryXrlfRecord() {
        var projectId = $("#xrlfProjectId").val();
        var owner = $("#owner").val();
        var visitor = $("#visitor").val();
        var phone = $("#phone2").val();
        var startDate= $("#openBeginDate3").val();
        var endDate= $("#openEndDate3").val();
        table.reload('xrlfRecordTable',{
            where: {projectId:projectId,owner:owner,visitor:visitor,phone:phone,
                startDate:startDate,endDate:endDate}
            ,page:  {
                curr:1
            }
        });
    }

    function queryCxlfRecord() {
        var projectId = $("#cxlfProjectId").val();
        var owner = $("#owner2").val();
        var carNo = $("#searchCarNo2").val();
        var phone = $("#phone3").val();
        var startDate= $("#openBeginDate4").val();
        var endDate= $("#openEndDate4").val();
        table.reload('cxlfRecordTable',{
            where: {projectId:projectId,owner:owner,carNo:carNo,phone:phone,
                startDate:startDate,endDate:endDate}
            ,page:  {
                curr:1
            }
        });
    }

});
//预览大小根据原图的大小决定弹窗的大小
let imgDiv;
function previewImg(obj) {
    var img = new Image();
    img.src = obj.src;
    var height = img.height + 50; //获取图片高度
    var width = img.width; //获取图片宽度
    var imgHtml = "<img onclick='closeLayer()' src='" + obj.src + "' width='100%' height='100%'/>";
    //弹出层
    imgDiv = layui.layer.open({
        type: 1,
        shade: 0.8,
        offset: 'auto',
        area: ['100%', '100%'],
        shadeClose: true,
        scrollbar: false,
        title: "抓拍图片预览",
        content: imgHtml,
        cancel: function () {
        }
    });
}
function closeLayer() {
    if(imgDiv){
        layui.layer.close(imgDiv);
    }
}